//
//  LoginService.m
//  YuanXinKit
//
//  Created by 晏德智 on 2016/11/23.
//  Copyright © 2016年 晏德智. All rights reserved.
//

#import "UserService.h"
#import "GlobalDeviceInfo.h"
#import "YuanXinKeyChainManager.h"
#import "AFOAuthCredential.h"
#import "NetworkingManager.h"



NSString *const Login_Url_Turing = @"/YuanXin.Platform.OAuthService/turing";
NSString *const Login_Url = @"/YuanXin.Platform.OAuthService/token";
NSString *const Logout_Url = @"/YuanXin.Platform.OAuthService/account/logout";

@implementation UserService

+ (instancetype)shareInstance{
    static UserService *_userService = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _userService = [[UserService alloc] init];
    });
    
    return _userService;
}

+ (void)loginParams:(NSDictionary *)paramDict
          success:(void (^)(NSDictionary *data))success
          failure:(void (^)(NSError *error))failure{
    
    void (^successBlock)(id data) =nil;
    if(success){
        successBlock = [success copy];
    }
    void (^errorBlock)(NSError *error) = nil;
    if(failure){
        errorBlock = [failure copy];
    }
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:@"password" forKey:@"grant_type"];
    [params setObject:[GlobalDeviceInfo shareInstance].appid forKey:@"client_id"];
    [params setObject:[GlobalDeviceInfo shareInstance].uniqueId forKey:@"deviceId"];
    [params addEntriesFromDictionary:paramDict];
    
    NSString *urlStr = Login_Url;
    if ([params.allKeys containsObject:@"isTuring"]) {
        urlStr = [RCTConvert BOOL:params[@"isTuring"]] ? Login_Url_Turing : Login_Url;
    }
    if ([[self shareInstance] loginAddress]) {
        // stringByAppendingPathComponent似乎能把多个斜杠改成一个，比如"https://"-->"https:/"，请求似乎不影响
        urlStr = [[[self shareInstance] loginAddress] stringByAppendingPathComponent:urlStr];
    }
    [[NetworkingManager shareInstance] authenticateUsingOAuthWithURLString:urlStr
                                                                parameters:params
                                                                   success:^(id responseObject) {
                                                                       if(successBlock){
                                                                           successBlock(responseObject);
                                                                       }
                                                                   } failure:^(NSError *error) {
                                                                       if(errorBlock){
                                                                           errorBlock(error);
                                                                       }
                                                                   }];
}

+ (void)loginOut:(void (^)(id))success failure:(void (^)(NSError *))failure {
    
    void (^successBlock)(id data) =nil;
    if(success){
        successBlock = [success copy];
    }
    void (^errorBlock)(NSError *error) = nil;
    if(failure){
        errorBlock = [failure copy];
    }
   
    [AFOAuthCredential deleteCredentialWithIdentifier:[GlobalDeviceInfo shareInstance].bundleId];
    [AFOAuthCredential deleteCredentialWithIdentifier:[GlobalDeviceInfo shareInstance].appid]; //todo:可以不根据bundleId
    
    NSString *urlStr = Logout_Url;
    if ([[self shareInstance] loginAddress]) {
        urlStr = [[[self shareInstance] loginAddress] stringByAppendingPathComponent:urlStr];
    }
    [[NetworkingManager shareInstance] POST:urlStr
                                parameters:nil
                                   success:^(NSURLSessionDataTask *task, id responseObject){
                                       
                                       if(successBlock){
                                           successBlock(@(1));
                                       }
                                   } failure:^(NSURLSessionDataTask *task, NSError * error) {
                                       NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
                                       NSInteger statuscode = response.statusCode;
                                       if(statuscode == 200 || statuscode == 401){
                                           if(successBlock){
                                               successBlock(@(1));
                                           }
                                       }else {
                                           if (errorBlock) {
                                               errorBlock(error);
                                           }
                                       }
                                   }];
}


+ (void)refreshToken:(void (^)(NSDictionary *data))success
             failure:(void (^)(NSError *error))failure{
    
    void (^successBlock)(id data) =nil;
    if(success){
        successBlock = [success copy];
    }
    void (^errorBlock)(NSError *error) = nil;
    if(failure){
        errorBlock = [failure copy];
    }
    // __weak typeof (self) weakSelf = self;
    AFOAuthCredential *credential = [AFOAuthCredential retrieveCredentialWithIdentifier:[GlobalDeviceInfo shareInstance].appid];
    if(!credential){
        //todo:过度一下批量退出登录的问题
        credential = [AFOAuthCredential retrieveCredentialWithIdentifier:[GlobalDeviceInfo shareInstance].bundleId];
    }
    if(credential && credential.refreshToken){
        NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
        [params setObject:@"refresh_token" forKey:@"grant_type"];
        [params setObject:credential.refreshToken forKey:@"refresh_token"];
        [params setObject:[GlobalDeviceInfo shareInstance].appid forKey:@"client_id"];
        [params setObject:[GlobalDeviceInfo shareInstance].uniqueId forKey:@"deviceId"];
        
        NSString *urlStr = Login_Url;
        if ([[self shareInstance] loginAddress]) {
            urlStr = [[[self shareInstance] loginAddress] stringByAppendingPathComponent:urlStr];
        }
        [[NetworkingManager shareInstance] authenticateUsingOAuthWithURLString:urlStr
                                                                    parameters:params
                                                                       success:^(id responseObject) {
                                                                           /*
                                                                            [AFOAuthCredential storeCredential:credential
                                                                            withIdentifier:[GlobalDeviceInfo shareInstance].bundleId];
                                                                            
                                                                            
                                                                            NSTimeInterval time = [credential.expiration timeIntervalSince1970];
                                                                            NSNumber *dTime = [NSNumber numberWithDouble:time];
                                                                            NSDictionary *resultData =@{
                                                                            @"access_token":credential.accessToken,
                                                                            @"refresh_token":credential.refreshToken,
                                                                            @"token_type":credential.tokenType,
                                                                            @"expires_in":dTime
                                                                            };
                                                                            */
                                                                           if(successBlock){
                                                                               successBlock(responseObject);
                                                                           }
                                                                       } failure:^(NSError *error) {
                                                                           if(errorBlock){
                                                                               errorBlock(error);
                                                                           }
                                                                       }];
    }else{
        if (errorBlock) {
            NSError *dError = [self createError:@(-1) errorMessage:@"请先登录" domain:@"validationerror"];
            errorBlock(dError);
        }
    }
}

+ (void)IMLogin:(void (^)(NSDictionary *data))success
        failure:(void (^)(NSError *error))failure{
    //@"account/imKey"
    //account/userProfile
    void (^successBlock)(id data) =nil;
    if(success){
        successBlock = [success copy];
    }
    void (^errorBlock)(NSError *error) = nil;
    if(failure){
        errorBlock = [failure copy];
    }
    
    NSString *urlStr = @"OAuthServices/account/imKey";
    if ([[self shareInstance] loginAddress]) {
        urlStr = [[[self shareInstance] loginAddress] stringByAppendingPathComponent:urlStr];
    }
    [[NetworkingManager shareInstance] POST:urlStr
                                 parameters:nil
                                    success:^(NSURLSessionDataTask *task, id responseObject){
                                        if(successBlock){
                                            successBlock(responseObject);
                                        }
                                    } failure:^(NSURLSessionDataTask *task, NSError * error) {
                                        if (errorBlock) {
                                            errorBlock(error);
                                        }
                                    }];
}

+ (NSError *)createError:(NSNumber *)code errorMessage:(NSString *)meaage domain:(NSString *)domain {
    NSDictionary *errorInfo = @{ NSLocalizedDescriptionKey: meaage };
    NSError *desError = [NSError errorWithDomain:domain code:code.integerValue userInfo:errorInfo];
    return desError;
}


+ (NSString *)getOAuthToken{
    
    NSString *token = nil;
    AFOAuthCredential *credential = [AFOAuthCredential retrieveCredentialWithIdentifier:[GlobalDeviceInfo shareInstance].appid];
    if(!credential){
        //todo:过度一下批量退出登录的问题
        credential = [AFOAuthCredential retrieveCredentialWithIdentifier:[GlobalDeviceInfo shareInstance].bundleId];
    }
    
    if(credential && credential.refreshToken){
        if(!credential.expired){
            token = credential.accessToken;
        }else{
            token = @"-1";
        }
    }
    
    return token;
}

@end
